const RouterPlugin = function() {
  this.$router = null
  this.$store = null
}

RouterPlugin.install = function(router, store) {
  this.$router = router
  this.$store = store
  function isURL(s) {
    return /^http[s]?:\/\/.*/.test(s)
  }
  this.$router.$flyrayRouter = {
    formatRoutes: function(menu = [], first) {
      const aRouter = []
      const propsDefault = {
        label: 'label',
        path: 'path',
        icon: 'icon',
        children: 'children',
        meta: 'meta',
        name: 'name',
        query:{menuId:"menuId"}
      }
      if (menu.length === 0) return []

      for (let i = 0; i < menu.length; i++) {
        
        const oMenu = menu[i]
        const children = oMenu['children']
        if(children == null){
          continue
        }
        const isChild = children.length !== 0
        //特殊处理组件
        const component = 'views' + oMenu.path
        const path = oMenu.path
        const name = oMenu.label
        const icon = oMenu.icon
        const menuId = oMenu.id
        const meta = {
          keepAlive: Number(oMenu['keepAlive']) === 0
        }
        var oRouter = {
          path: path,
          name: name,
          query:{menuId : menuId},
          component(resolve) {
            // 判断是否为首路由
            if (first) {
              require(['@/views/Index'], resolve)
              // 判断是否为多层路由
            }else {
              require([`../${component}`], resolve)
            }
          },
          redirect: (() => {i
            if (isChild && first && !isURL(path)) return `${path}/index`
            else return ''
          })(),
          //redirect: `${path}/index`,
          // 处理是否为一级路由
          children: !isChild ? (() => {
            if (first) {
              return [{
                component(resolve) { require([`../${component}.vue`], resolve) },
                icon: icon,
                name: name,
                meta: meta,
                path: 'index',
                query:{menuId : menuId}
              }]
            }
            return []
          })() : (() => {
            return this.formatRoutes(children, false)
          })()
        }
        aRouter.push(oRouter)
      }
      return aRouter
    }
  }
}

export default RouterPlugin